import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';

const DonutChart = () => {
  const chartRef = useRef<HTMLDivElement>(null);
  let chartInstance: echarts.ECharts | null = null; // 明确类型

  // 图表数据
  const donutData = [
    { value: 335, name: 'A' },
    { value: 310, name: 'B' },
    { value: 234, name: 'C' },
    { value: 135, name: 'D' },
    { value: 1548, name: 'E' },
  ];

  const legendData = ['A', 'B', 'C', 'D', 'E'];

  useEffect(() => {
    if (chartRef.current) {
      chartInstance = echarts.init(chartRef.current);

      const option = {
        legend: {
          orient: 'vertical',
          left: 'left',
          data: legendData,
        },
        series: [
          {
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center',
            },
            labelLine: {
              show: false,
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '30',
                fontWeight: 'bold',
              },
            },
            data: donutData,
          },
        ],
      };

      chartInstance.setOption(option);
    }

    return () => {
      if (chartInstance) {
        chartInstance.dispose();
      }
    };
  }, []);

  return <div ref={chartRef} style={{ width: '100%', height: '100%' }} />;
};

export default DonutChart;